package com.quzhi.sys.controller.warehouseController;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quzhi.common.Result;
import com.quzhi.common.Utils;
import com.quzhi.sys.dto.TransferRecordDto;
import com.quzhi.sys.entity.Inventory;
import com.quzhi.sys.entity.TransferGoods;
import com.quzhi.sys.entity.TransferRecord;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器 库存调拨控制器
 *
 * </p>
 *
 * @author Xibing
 * @since 2024-07-23
 */

@Slf4j
@RestController
@RequestMapping("/sys/transferRecord")
public class TransferRecordController {
    @Autowired
    private TransferRecordServiceImpl transferRecordService;


    @Autowired
    private InventoryServiceImpl inventoryService;

    @Autowired
    private TransferGoodsServiceImpl transferGoodsService;

    @Autowired
    private WarehouseServiceImpl warehouseService;


    @Autowired
    private UserServiceImpl userService;

    // 查询调拨记录
    @GetMapping("/list")
    public Result<?> getTransferRecord(
            @RequestParam(value = "transferId", required = false) String transferId,
            @RequestParam(value = "outWarehouseId", required = false) String outWarehouseId,
            @RequestParam(value = "saveWarehouseId", required = false) String saveWarehouseId,
            @RequestParam(value = "pageNo") Long pageNo,
            @RequestParam(value = "pageSize") Long pageSize) {

        // 更具日期排序

        LambdaQueryWrapper<TransferRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(TransferRecord::getCreateTime);
        wrapper.like(StringUtils.hasLength(transferId), TransferRecord::getTransferId, transferId);
        wrapper.eq(StringUtils.hasLength(outWarehouseId), TransferRecord::getOutWarehouseId, outWarehouseId);
        wrapper.eq(StringUtils.hasLength(saveWarehouseId), TransferRecord::getSaveWarehouseId, saveWarehouseId);
        Page<TransferRecord> infoPage = new Page<>(pageNo, pageSize);
        transferRecordService.page(infoPage, wrapper);

        List<TransferRecord> records = infoPage.getRecords();

        // d获取仓库名称所有仓库名称和Id
        List<Map<String, String>> allWarehouseNameAndId = warehouseService.getAllWarehouseNameAndId();

        List<Map<String, Object>> rows = new ArrayList<>();
        for (TransferRecord record : records) {
            Map<String, Object> transferRecord = new HashMap<>();
            transferRecord.put("transferId", record.getTransferId());

            // 调出仓库名称
            for (Map<String, String> warehouseNameAndId : allWarehouseNameAndId) {
                // 更具Id获取仓库名称
                if (warehouseNameAndId.get("warehouseId").equals(record.getOutWarehouseId())) {
                    transferRecord.put("outWarehouseName", warehouseNameAndId.get("warehouseName"));
                }
            }

            // 调如仓库名称
            for (Map<String, String> warehouseNameAndId : allWarehouseNameAndId) {
                // 更具Id获取仓库名称
                if (warehouseNameAndId.get("warehouseId").equals(record.getSaveWarehouseId())) {
                    transferRecord.put("saveWarehouseName", warehouseNameAndId.get("warehouseName"));
                }
            }

            // 调出仓库
            transferRecord.put("operator", record.getOperator());
            transferRecord.put("createTime", record.getCreateTime());
            transferRecord.put("remark", record.getRemark());

            rows.add(transferRecord);
        }


        Map<String, Object> data = new HashMap<>();

        data.put("rows", rows);
        data.put("total", infoPage.getTotal());


        return Result.success(data);
    }


    // 查询所有调拨商品数量

    /**
     * @param pageNo
     * @param pageSize
     * @return 返回[{商品名称：goodsName，调拨数量：num}]
     */
    @GetMapping("/getAllTransferGoodsNum")
    public Result<?> getAllTransferGoodsNum(
            @RequestParam(value = "transferId", required = false) String transferId,
            @RequestParam(value = "outWarehouseId", required = false) String outWarehouseId,
            @RequestParam(value = "saveWarehouseId", required = false) String saveWarehouseId,
            @RequestParam(value = "pageNo") Long pageNo,
            @RequestParam(value = "pageSize") Long pageSize) {
        // 更具日期排序


        LambdaQueryWrapper<TransferRecord> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.hasLength(transferId), TransferRecord::getTransferId, transferId);
        wrapper.eq(StringUtils.hasLength(outWarehouseId), TransferRecord::getOutWarehouseId, outWarehouseId);
        wrapper.eq(StringUtils.hasLength(saveWarehouseId), TransferRecord::getSaveWarehouseId, saveWarehouseId);
        wrapper.orderByDesc(TransferRecord::getCreateTime);
        Page<TransferRecord> infoPage = new Page<>(pageNo, pageSize);
        transferRecordService.page(infoPage, wrapper);

        // 获取所有调拨清单
        List<TransferRecord> records = infoPage.getRecords();
        List<Map<String, Object>> allTransferNumber = new ArrayList<>();

        for (TransferRecord record : records) {
            // 更具调拨单号查询所有调拨序列号，更具序列号Id查询商品名称
            String recordTransferId = record.getTransferId(); // 调拨单号
            LambdaQueryWrapper<TransferGoods> transferGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            transferGoodsLambdaQueryWrapper.eq(TransferGoods::getTransferRecordId, recordTransferId);
            // 获取该调拨单号的所有调拨序列号
            List<TransferGoods> transferGoods = transferGoodsService.list(transferGoodsLambdaQueryWrapper);
            // 统计有几种设备，每种设备有多少个
            // 记录所有设备名字，和数字
            Map<String, Object> goods = new HashMap<>();
            for (TransferGoods transferGood : transferGoods) {
                goods.putIfAbsent(transferGood.getGoodsName(), 0);
                if (goods.containsKey(transferGood.getGoodsName())) {
                    goods.put(transferGood.getGoodsName(), (Integer) goods.get(transferGood.getGoodsName()) + 1);
                }
            }
            goods.put("transferId", record.getTransferId());

            allTransferNumber.add(goods);
        }

        return Result.success(allTransferNumber);
    }

    /**
     * 调拨详情
     */
    @GetMapping("/{transferId}")
    public Result<?> getTransferInfo(@PathVariable String transferId){
        // 更具调拨单号查询调拨设备
        LambdaQueryWrapper<TransferGoods> transferGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        transferGoodsLambdaQueryWrapper.eq(TransferGoods::getTransferRecordId, transferId);
        List<TransferGoods> transferGoodsList = transferGoodsService.list(transferGoodsLambdaQueryWrapper);

        List<Map<String, Object>> data = new ArrayList<>();

        for (TransferGoods transferGoods : transferGoodsList) {
            Map<String, Object> row = new HashMap<>();

            // 商品名称
            row.put("goodsName", transferGoods.getGoodsName());

            // 序列号
            Inventory inventory = inventoryService.getById(transferGoods.getInventoryId());
            row.put("serialNumber", inventory.getSerialNumber());

            data.add(row);
        }

        return Result.success(data);
    }



    // 添加库存调拨记录
    @PostMapping
    public Result<?> addTransfer(@RequestBody TransferRecordDto transferRecordDto, HttpServletRequest request) {
        log.error(transferRecordDto.getInventorys().toString());
        TransferRecord transferRecord = new TransferRecord();

        // 生成调拨单号
        String db = Utils.generateRandomNumberString("DB");


        // 获取当前用户名称
        String token = request.getHeader("qz-Token");
        Map<String, Object> userinfo = userService.getUserinfo(token);

        String name = (String) userinfo.get("name");
        // 调拨单
        transferRecord.setTransferId(db);
        transferRecord.setOutWarehouseId(transferRecordDto.getOutWarehouseId());
        transferRecord.setSaveWarehouseId(transferRecordDto.getSaveWarehouseId());
        transferRecord.setRemark(transferRecordDto.getRemark());
        transferRecord.setCreateTime(LocalDateTime.now());
        transferRecord.setOperator(name);

        // 保存
        transferRecordService.save(transferRecord);

        List<Map<String, String>> SendInventorys = transferRecordDto.getInventorys();

        // 调拨商品
        // 查询所有商品
        LambdaQueryWrapper<Inventory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Inventory::getWarehouseId, transferRecord.getOutWarehouseId());
        List<Inventory> inventories = inventoryService.list(lambdaQueryWrapper);


        for (Map<String, String> inventory : SendInventorys) {
            // 调拨记录
            TransferGoods transferGoods = new TransferGoods();
            transferGoods.setId(UUID.randomUUID().toString());

            transferGoods.setTransferRecordId(transferRecord.getTransferId());


            // 调拨库存
            for (Inventory i : inventories) {
                // 查询
                if (i.getId().equals(inventory.get("inventoryId"))) {
                    // 调拨
                    i.setWarehouseId(transferRecord.getSaveWarehouseId());
                    inventoryService.updateById(i);

                    transferGoods.setInventoryId(inventory.get("inventoryId"));
                    transferGoods.setGoodsName(inventory.get("goodsName"));
                    log.error(transferGoods.getGoodsName());

                    //   保存调拨记录
                    transferGoodsService.save(transferGoods);
                    break;
                }
            }
        }
        return Result.success("调拨成功");
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteById(@PathVariable("id") String id, HttpServletRequest request) {
        // 获取当前用户名称
        String token = request.getHeader("qz-Token");
        User loginUser = userService.getUserinfoForBack(token);

        if (loginUser != null) {
            // 删除仓库
            String role = loginUser.getRole();
            if (role.equals("admin")) {
                // 更具调拨单号查询调拨商品，将调拨的记录也删除
                LambdaQueryWrapper<TransferGoods> transferGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                transferGoodsLambdaQueryWrapper.eq(TransferGoods::getTransferRecordId, id);
                transferGoodsService.remove(transferGoodsLambdaQueryWrapper);

                LambdaQueryWrapper<TransferRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TransferRecord::getTransferId, id);
                transferRecordService.remove(wrapper);

                return Result.success("删除成功");
            } else {
                return Result.fail(20002, "你没有权限执行此操作");
            }
        } else {
            return Result.fail(20002, "删除失败");
        }

    }

}
